package cn.edu.gzmtu.dao;

import cn.edu.gzmtu.domain.Permission;
import cn.edu.gzmtu.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface IRoleDao {

    /**
     * 根据用户id查询所有对应的角色
     * @param userId
     * @return
     * @throws Exception
     */
    @Select("select * from role where id in(select roleId from users_role where userid=#{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", javaType = java.util.List.class, many = @Many(select = "cn.edu.gzmtu.dao.IPermissionDao.findPermissionByRoleId"))
    })
    List<Role> findRoleByUserId(String userId) throws Exception;

    /**
     * 查询所有角色
     * @return
     */
    @Select("select * from role")
    List<Role> findAll() throws Exception;

    /**
     * 添加角色
     * @param role
     */
    @Insert("insert into role(roleName, roleDesc) values(#{roleName}, #{roleDesc})")
    void save(Role role);

    /**
     * 根据id查询角色
     * @param id
     * @return
     */
    @Select("select * from role where id=#{id}")
    Role findById(String id);

    /**
     * 查询角色没有的权限
     * @param id
     * @return
     */
    @Select("select * from permission where id not in (select permissionId from role_permission where roleId=#{id})")
    List<Permission> findRoleOtherPermission(String id);

    /**
     * 为角色添加权限
     * @param permissionId
     */
    @Insert("insert into role_permission(permissionId, roleId) values(#{permissionId}, #{roleId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId) throws Exception;
}
